<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class User {
      ajax(user) {
        let url = 'http://localhost:3000/posts';
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("GET", url);
          xhr.send();
          xhr.onload = function () {
            if (this.status === 200) {
              resolve(JSON.parse(this.response))
            } else if (this.status === 404) {
              reject('404') // 这里是异步，不能throw 
            } else {
              reject("加载失败")
            }
          }
          xhr.onerror = function () {
            reject(this)
          }
        })
      }
      render(users) {
        users.reduce((promise, user) => {
          return promise.then(_ => {
            return this.ajax(user)
          }).then(user => {
            return this.view(user)
          })
        }, Promise.resolve())
      }
      view(user) {
        return new Promise(resolve => {
          console.log(user)
          resolve()
        })
      }
    }
    new User().render(['p1', 'p2'])
  </script>
</body>

</html>